package com.op.teachingliteapp.activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.op.teachingliteapp.R;
import com.op.teachingliteapp.service.LoginService;
import com.op.teachingliteapp.service.UserService;
import com.op.teachingliteapp.util.IntentUtils;
import com.op.teachingliteapp.util.StringUtils;
import com.op.teachingliteapp.util.ToastUtils;
import com.op.teachingliteapp.util.network.NetworkUtils;

/**
 * 显示欢迎界面，并进行相应的登录跳转
 * 
 * @author Michael
 * 
 */
public class SplashActivity extends Activity {

	private static final String TAG = SplashActivity.class.getSimpleName();
	private final long splashDelay = 2000L;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);
		login();
	}

	/**
	 * 登录跳转
	 * 
	 * <ol>
	 * <li>无自动登录，跳转LoginActivity</li>
	 * <li>有自动登录，无网络，跳转HomeActivity</li>
	 * <li>有自动登录，有网络，联网登录</li>
	 * <li>有自动登录，网络异常，跳转LoginActivity</li>
	 * </ol>
	 */
	private void login() {
		if (!LoginService.isAutoLogin()) {
			splash(splashDelay, LoginActivity.class); // 持续2秒后跳转
		} else {
			if (!NetworkUtils.isNetworkAvailable(this)) {
				splash(splashDelay, HomeActivity.class); // 持续2秒后跳转
			} else {
				LoginService.syncLogin(UserService.getUserNumber(), UserService.getUserPwd(),
						new Response.Listener<String>() {

							@Override
							public void onResponse(String response) {
								Log.i(TAG, response);
								handleLoginResponse(response);
							}
						}, new Response.ErrorListener() {

							@Override
							public void onErrorResponse(VolleyError error) {
								Log.e(TAG, error.getMessage(), error);
								ToastUtils
										.show(SplashActivity.this, R.string.tips_login_sync_error);
								splash(splashDelay, LoginActivity.class);
							}
						});
			}
		}
	}

	/**
	 * 处理联网登录响应
	 * 
	 * <ol>
	 * <li>登录验证为空，跳转HomeActivity</li>
	 * <li>登录验证成功，跳转HomeActivity</li>
	 * <li>登录验证失败，跳转LoginActivity</li>
	 * </ol>
	 */
	private void handleLoginResponse(String response) {
		// 获取数据为空，跳转HomeActivity
		if (StringUtils.isEmptyOrStringNull(response)) {
			splash(splashDelay, HomeActivity.class);
			return;
		}

		LoginService loginService = new LoginService(this, response);
		if (loginService.isSyncLogin()) {
			loginService.saveData();
			splash(splashDelay, HomeActivity.class);
		} else {
			splash(splashDelay, LoginActivity.class);
		}
	}

	/**
	 * 持续指定时间后跳转
	 */
	private void splash(long delayMillis, final Class<?> cls) {

		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				IntentUtils.jump(SplashActivity.this, cls);
				finish();
			}
		}, delayMillis);
	}

}
